import paho.mqtt.client as mqtt
import time

class MQTTServer:
    _instance = None
    topics = []

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.mqtt = mqtt.Client()
            # MQTT代理设置
            mqtt_broker = "8.137.99.64"
            mqtt_port = 1883
            mqtt_user = "zhaonx"
            mqtt_password = "Zhaonx123.."

            # 创建MQTT客户端
            cls._instance.client = mqtt.Client(client_id="xxxx")
            # 设置用户名和密码（如果需要）
            cls._instance.client.username_pw_set(mqtt_user, mqtt_password)
            # 绑定回调函数
            cls._instance.client.on_connect = cls._instance.on_connect
            cls._instance.client.on_message = cls._instance.on_message
            print("MQTT connect......")
            # 连接到MQTT代理
            cls._instance.client.connect(mqtt_broker, mqtt_port, 60)
            # 开始循环以处理网络流量
            cls._instance.client.loop_start()
        return cls._instance

    def sendMsg(self, topic, msg):# 发送消息
        self.client.publish(topic, msg)

    def subscribe(self, topic):# 订阅
        self.client.subscribe(topic)

    def disconnect(self):  # 停止循环并断开连接
        self.client.loop_stop()
        self.client.disconnect()

    def onMessage(self, func):
        self.onMessage = func

    def on_connect(self,client, userdata, flags, rc): # 链接成功
        # print("MQTT on_connect")
        # 订阅
        for topic in self.topics:
            self.client.subscribe(topic)

    def on_message(self,client, userdata, msg):# 接收到消息
        # print(f"Message received: {msg.topic} {msg.payload.decode()}")
        if self.onMessage:
            self.onMessage(msg.topic,msg.payload.decode())





# mq = MQTTServer(host="8.137.99.64")
# mq.topics = ["A"]
#
# while True:
#     print("。。。")
#     time.sleep(10)